import 'package:flutter/material.dart';
import 'package:flutter_chip/view/forum/view_forumlist.dart';

class ForumPage extends StatefulWidget {
  @override
  _ForumPageState createState() => _ForumPageState();
}

class _ForumPageState extends State<ForumPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  var tabs = ["关注", "推荐", "问答", "51单片机", "C语言", "蓝牙助手"];
  PageController pageController;
  TabController tabController;
  int page = 0;
  var isPageCanChanged = true;

  @override
  void initState() {
    super.initState();
    pageController = PageController(initialPage: 1);
    tabController =
        TabController(length: tabs.length, vsync: this, initialIndex: 1);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        onPageChange(tabController.index, p: pageController);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          elevation: 0,
          backgroundColor: Theme.of(context).canvasColor,
          title: TabBar(
              controller: tabController,
              labelColor: Color(0xff333333),
              unselectedLabelColor: Color(0xff999999),
              indicatorColor: Color(0xff333333),
              isScrollable: true,
              onTap: (value) {
                pageController.jumpToPage(value);
              },
              indicatorSize: TabBarIndicatorSize.label,
              tabs: tabs.map((item) {
                return Tab(child: Text(item, style: TextStyle(fontSize: 16)));
              }).toList())),
      body: PageView(
        controller: pageController,
        onPageChanged: (index) {
          if (isPageCanChanged) {
            onPageChange(index);
          }
        },
        children: tabs.map((item) {
          return ForumListPage(title: item);
        }).toList(),
      ),
    );
  }

  ///页面滑动监听
  onPageChange(int index, {PageController p, TabController t}) async {
    if (p != null) {
      //判断是哪一个切换
      isPageCanChanged = false;
      await pageController.animateToPage(index,
          duration: Duration(milliseconds: 500), curve: Curves.ease);
      isPageCanChanged = true;
    } else {
      tabController.animateTo(index);
    }
  }

  @override
  bool get wantKeepAlive => true;
}
